package com.zysf.library_boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zysf.library_boot.dto.LendDto;
import com.zysf.library_boot.dto.PostsDto;
import com.zysf.library_boot.entity.Notice;
import com.zysf.library_boot.entity.Posts;
import com.zysf.library_boot.service.PostsService;
import com.zysf.library_boot.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/posts")
public class PostsController {

    @Autowired
    PostsService postsService;

    @RequestMapping("/getMyPosts")
    public Result getMyPosts(@RequestParam Integer id,@RequestParam int currentPage, @RequestParam int pageSize,@RequestParam String content) {
        Page<Posts> page = new Page<>(currentPage, pageSize);
        QueryWrapper<Posts> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("readerid", id);
        if (content != null && !content.isEmpty()) {
            queryWrapper.like("content", content);
        }
        IPage<Posts> postsPage = postsService.page(page, queryWrapper);

        Map<String, Object> result = new HashMap<>();
        result.put("records", postsPage.getRecords());
        result.put("total", postsPage.getTotal());

        return Result.ok(result);
    }

    @PostMapping("/addPosts")
    public Result addPosts(@RequestBody Posts posts) {
        boolean saved = postsService.save(posts);
        if (saved) {
            return Result.ok("添加成功");
        } else {
            return Result.fail("添加失败");
        }
    }

    @RequestMapping("/deleteById")
    public Result deleteById(Integer id){
        boolean c = postsService.removeById(id);
        return Result.ok(c);
    }

    @RequestMapping("/batchDeletePosts")
    public Result batchDeletePosts(@RequestBody List<Integer> ids){
        boolean d = postsService.removeBatchByIds(ids);
        return Result.ok(d);
    }

    @RequestMapping("/getCustomPosts")
    public Result getCustomPosts(@RequestParam(required = false) String content,
                                    @RequestParam int currentPage,
                                    @RequestParam int pageSize) {
        Page<PostsDto> page = new Page<>(currentPage, pageSize);
        IPage<PostsDto> postsDtoIPage = postsService.getCustomPosts(page,content);

        Map<String, Object> result = new HashMap<>();
        result.put("records", postsDtoIPage.getRecords());
        result.put("total", postsDtoIPage.getTotal());

        return Result.ok(result);
    }
}
